package com.springboot.dao.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.springboot.bean.PropertiesBean;

@Configuration
@MapperScan(basePackages = Test1DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "test1SqlSessionFactory")
public class Test1DataSourceConfig {
	public static final String PACKAGE = "com.springboot.mapper.test1";

	@Autowired
	private PropertiesBean propertiesBean;

	@Bean(name = "test1DataSource")
	@Primary
	public DataSource test1DataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(propertiesBean.getMysqlDriverClassName());
		dataSource.setUrl(propertiesBean.getDb1Url());
		dataSource.setUsername(propertiesBean.getDb1User());
		dataSource.setPassword(propertiesBean.getDb1Password());
		return dataSource;
	}

	@Bean(name = "test1TransactionManager")
	@Primary
	public DataSourceTransactionManager test1TransactionManager(
			@Qualifier("test1DataSource") DataSource test1DataSource) {
		return new DataSourceTransactionManager(test1DataSource);
	}

	@Bean(name = "test1SqlSessionFactory")
	@Primary
	public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource test1DataSource)
			throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(test1DataSource);
		return sessionFactory.getObject();
	}

}
